package com.itheima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.dto.ArticleHomeDto;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.mapper.ApArticleConfigMapper;
import com.itheima.article.mapper.ApArticleContentMapper;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.vo.ArticleInfoVo;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.pojo.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description <p>已发布的文章信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.article.service.impl
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private WmNewsFeign wmNewsFeign;

    /**
     * 1.同步自媒体文章到文章微服
     * @param dto
     */
    @Override
    @Transactional
    public void saveArticleInfo(ArticleInfoDto dto) {
        log.info("文章微服：开始同步文章信息");
        //1.保存文章表数据
        ApArticle apArticle = dto.getApArticle();
        // 是否有旧文章id
        Long articleId = apArticle.getId();
        if (null!=articleId){
            // 有旧文章
            //删除旧文章相关数据
            removeById(articleId);
            Map<String,Object> queryMap = Collections.singletonMap("article_id",articleId);
            // 删除文章内容表
            apArticleContentMapper.deleteByMap(queryMap);
            // 删除文章配置表
            apArticleConfigMapper.deleteByMap(queryMap);
            // 置为空值，是为了产生新的id
            apArticle.setId(null);
        }

        save(apArticle);
        log.info("保存文章信息成功...");
        // 获取新增的文章id
        articleId = apArticle.getId();
        //2.保存文章内容
        ApArticleContent apArticleContent = dto.getApArticleContent();
        apArticleContent.setArticleId(articleId);
        apArticleContentMapper.insert(apArticleContent);
        log.info("保存文章内容成功...");
        //3.保存文章配置
        ApArticleConfig apArticleConfig = dto.getApArticleConfig();
        apArticleConfig.setArticleId(articleId);
        apArticleConfigMapper.insert(apArticleConfig);
        log.info("保存文章配置成功...");
        //4.更新自媒体文章的状态，文章的article_id
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getWmNesId());
        //wmNews中的id要用long类型
        wmNews.setArticleId(articleId);
        // 状态为已发布
        wmNews.setStatus(BusinessConstants.WmNewsConstants.STATUS_PUBLISHED);
        // 发布后为上架状态，这一句为第10天优化
        wmNews.setEnable(BusinessConstants.WmNewsConstants.ENABLE_ON);
        ResultVo<WmNews> updateResult = wmNewsFeign.update(wmNews);
        if (!updateResult.isSuccess()){
            //没更新成功，报错让事务回滚
            throw new LeadNewsException("远程调用更新自媒体文章状态失败. 文章数据同步");
        }
        log.info("远程调用更新自媒体文章状态成功...");
    }


    /**
     * app端文章列表
     *
     * @param dto
     * @param loadType
     * @return
     */
    @Override
    public PageResultVo<ApArticle> findPage(ArticleHomeDto dto, int loadType) {
        //1. 参数校验
        if (null==dto){
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 条件中时间处理，如果没有值，则使用当前系统时间
        if (dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //3. 分页查询
        IPage<ApArticle> pageInfo = new Page<>(dto.getLoaddir(),dto.getSize());

        // 查询，在mapper中自定义findPage方法，需要配置映射文件。
        List<ApArticle> list = getBaseMapper().findPage(pageInfo,dto,loadType);

        //4. 构建结果返回
        return PageResultVo.pageResult(dto.getLoaddir(),dto.getSize(), pageInfo.getTotal(),list);
    }

    /**
     * 查询文章详情
     * @param paramMap
     * @return
     */
    @Override
    public ArticleInfoVo loadArticleInfo(Map<String, String> paramMap) {
        //先查询配置表
        long articleId = Long.parseLong(paramMap.get("articleId"));
        // select * from ap_article_config where is_down=0 and is_delete=0 and article_id=?
        LambdaQueryWrapper<ApArticleConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleConfig::getIsDown,0).eq(ApArticleConfig::getIsDelete,0)
                .eq(ApArticleConfig::getArticleId,articleId);
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(queryWrapper);
        //配置表是否存在记录
        if (null==apArticleConfig){
            // 不存在则报错
            throw new LeadNewsException(HttpCodeEnum.DATA_NOT_EXIST);
        }
        // 存在则查询内容表
        LambdaQueryWrapper<ApArticleContent> contentQueryWrapper = Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(contentQueryWrapper);
        // 组装articleInfoVo返回
        ArticleInfoVo articleInfoVo = new ArticleInfoVo();
        articleInfoVo.setContent(apArticleContent);
        articleInfoVo.setConfig(apArticleConfig);
        return articleInfoVo;
    }
}
